package com.baiduspring.elasticsearch.operation;

import com.baiduspring.function.elasticsearch.error.ElasticSearchException;
import org.apache.log4j.Logger;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsRequest;
import org.elasticsearch.action.admin.indices.exists.indices.IndicesExistsResponse;
import org.elasticsearch.client.transport.TransportClient;

/**
 * elasticSearch相关操作的工具集合
 */
public class EsUtils {
    private static final Logger LOGGER = Logger.getLogger(EsUtils.class);

    /**
     * 判断给定的索引是否存在
     *
     * @param transportClient 　ｅｓ客户端对象
     * @param index           　索引名
     * @return　返回布尔值　true: 存在, false: 不存在
     */
    public static boolean isIndexExists(TransportClient transportClient, String index) {
        IndicesExistsResponse response = transportClient.admin().indices().exists(new IndicesExistsRequest().indices(new String[]{index})).actionGet();
        return response.isExists();
    }

    /**
     * 创建索引
     *
     * @param transportClient 　ｅｓ客户端
     * @param indexName       　索引名
     * @return　返回布尔值 true：成功　　false：失败
     */
    public static boolean createIndex(TransportClient transportClient, String indexName) throws ElasticSearchException {
        if (!isIndexExists(transportClient, indexName)) {
            try {
                CreateIndexResponse response = transportClient.admin().indices().prepareCreate(indexName).get();
                return response.isAcknowledged();
            } catch (ElasticSearchException e) {
                LOGGER.error("索引创建失败，错误原因：", e);
                return false;
            } catch (Exception e) {
                LOGGER.error("索引创建失败，错误原因：", e);
            }
        }
        return true;
    }

//    public static boolean deleteIndex(TransportClient transportClient, String indexName) throws ElasticSearchException {
//        if (!isIndexExists(transportClient, indexName)) {
//            try {
//                CreateIndexResponse response = transportClient.admin().indices().prepareDelete(indexName).execute();
//                return response.isAcknowledged();
//            } catch (ElasticSearchException e) {
//                LOGGER.error("索引创建失败，错误原因：", e);
//                return false;
//            } catch (Exception e) {
//                LOGGER.error("索引创建失败，错误原因：", e);
//            }
//        }
//        return true;
//    }
}
